﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Media.Media3D.Converters;
using LiteDB;
using Simple_search.Data;

namespace Simple_search.Service
{
    public class CacheManager : IDisposable
    {
        private LiteDatabase database;

        public Options? Options { get; set; }
        private LiteCollection<Options> optionsCollection;

        private LiteCollection<BookInfo> booksCollection;
        
        public CacheManager()
        {
            string localAppDir = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
            string databaseDir = Path.Combine(localAppDir, "SimpleSearch_OpenTCM");
            Directory.CreateDirectory(databaseDir);
            database = new(Path.Combine(databaseDir, "cache.db"));
            booksCollection = (LiteCollection<BookInfo>)database.GetCollection<BookInfo>("Books");
            optionsCollection = (LiteCollection<Options>)database.GetCollection<Options>("Options");
            List<Options> options = optionsCollection.FindAll().ToList<Options>();
            if (options.Count() == 0)
            {
                Options = null;
            }
            else
            {
                Options = options[0];
            }
        }

        public void UpdateOptions(Options options)
        {
            if (Options == null)
            {
                optionsCollection.Insert(options);
                Options = options;
            } else
            {
                Options.Update(options);
                optionsCollection.Update(Options);
            }
        }

        public string? GetBookEncode(string bookFilePath)
        {
            List<string> encodeName = booksCollection.Query().Where(x => x.BookFilePath == bookFilePath).Select(X => X.EncodeName).ToList();
            if (encodeName.Count() > 0)
            {
                return encodeName[0];
            }
            else
            {
                return null;
            }
        }

        public void SaveBookInfo(string bookFilePath, string encodeName)
        {
            BookInfo? bookInfo = booksCollection.FindOne(x => x.BookFilePath == bookFilePath);
            if (bookInfo != null)
            {
                bookInfo.EncodeName = encodeName;
                booksCollection.Update(bookInfo);
            }
            else
            {
                booksCollection.Insert(new BookInfo() { BookFilePath = bookFilePath, EncodeName = encodeName });
            }
            booksCollection.EnsureIndex(x => x.BookFilePath);
        }

        public void Dispose()
        {
            database.Dispose();
        }
    }
}
